<template>
    <div>
        <p>
            <!--模态框(Modal)插件的触发按钮-->
            <button v-on:click="add()" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-edit"></i>
                新增
            </button>
            &nbsp;
            <!--刷新按钮-->
            <button v-on:click="getList(1)" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-refresh"></i>
                刷新
            </button>
        </p>
        <!--pagination可选参数：v-bind:itemCount="8" 不设置默认显示5个按钮，设置最多显示8个按钮-->
        <pagination ref="pagination" v-bind:list="getList"></pagination>

        <table id="simple-table" class="table  table-bordered table-hover">
                <thead>
                <tr>
                                    <th>角色</th>
                    <th>描述</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>

                <tr v-for="role in roles">
                    <td>{{role.name}}</td>
                    <td>{{role.desc}}</td>
                    <td>
                        <div class="hidden-sm hidden-xs btn-group">

                            <button v-on:click="unfoldAuthWindow(role)" class="btn btn-xs btn-info">
                                <i class="ace-icon fa fa-user bigger-120"></i>
                                <i class="ace-icon glyphicon glyphicon-check"></i>
                            </button>

                            <button  v-on:click="unfoldResourceWindow(role)" class="btn btn-xs btn-info">
                                <i class="ace-icon glyphicon glyphicon-list"></i>
                            </button>

                            <button  v-on:click="edit(role)" class="btn btn-xs btn-info">
                                <i class="ace-icon fa fa-pencil bigger-120"></i>
                            </button>

                            <button v-on:click="del(role.id)" class="btn btn-xs btn-danger">
                                <i class="ace-icon fa fa-trash-o bigger-120"></i>
                            </button>

                        </div>

                        <div class="hidden-md hidden-lg">
                            <div class="inline pos-rel">
                                <button class="btn btn-minier btn-primary dropdown-toggle" data-toggle="dropdown" data-position="auto">
                                    <i class="ace-icon fa fa-cog icon-only bigger-110"></i>
                                </button>

                                <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
                                    <li>
                                        <a href="#" class="tooltip-info" data-rel="tooltip" title="View">
																			<span class="blue">
																				<i class="ace-icon fa fa-search-plus bigger-120"></i>
																			</span>
                                        </a>
                                    </li>

                                    <li>
                                        <a href="#" class="tooltip-success" data-rel="tooltip" title="Edit">
																			<span class="green">
																				<i class="ace-icon fa fa-pencil-square-o bigger-120"></i>
																			</span>
                                        </a>
                                    </li>

                                    <li>
                                        <a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
																			<span class="red">
																				<i class="ace-icon fa fa-trash-o bigger-120"></i>
																			</span>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <!--用户获取角色权限模态框-->
        <div id="auth-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h6 class="modal-title">将用户添加到右边赋予角色权限</h6>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div></div>
                                <table id="user-table" class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th colspan="2">未有<span style="color: red">{{role.name}}</span>角色的用户</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="(user) in users">
                                            <td :id="generatorId(user)"
                                                class="td-padding-right"
                                                 v-on:click="addAuth(user)" >
                                                <a href="javascript:;" class="text-justify aastyle">
                                                    {{user.loginName}}
                                                </a>
                                            </td>
                                            <td class="text-right min td-padding-left">
                                                <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table id="role-user-table" class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th colspan="3">即将拥有<span style="color: red">{{role.name}}</span>角色的用户</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="user in roleUsers">
                                            <td :id="generatorIdIdx(user)"
                                                class=" td-padding-right"
                                                v-on:click="removeRoleForUser(user)" >
                                                <a href="javascript:;" class="text-justify aastyle">
                                                    {{user.loginName}}
                                                </a>
                                            </td>
                                            <td class="text-right min td-padding-left">
                                                <i class="ace-icon fa fa-trash blue"></i>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <miniPagination ref="miniPagination" v-bind:list="getUserPage" v-bind:itemCount="2"></miniPagination>
                            </div>
                            <div class="col-md-6">
                                <miniPagination1 ref="miniPagination1" v-bind:list="getRoleUsersPage" v-bind:itemCount="2"></miniPagination1>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
                            <i class="ace-icon fa fa-times"></i>
                            关闭
                        </button>
                        <button v-on:click="authUsers()" type="button" class="btn btn-white btn-info btn-round">
                            <i class="ace-icon fa fa-plus blue"></i>
                            授权
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->


        <!--资源展示模态框-->
        <div id="resource-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">角色权限许可</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <div class="col-sm-10">
                                    <ul id="tree" class="ztree"></ul>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button v-on:click="send(role)" type="button" class="btn btn-primary">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>

        <!--摸态框插件的实体html-->
        <div id="form-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">表单</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">角色</label>
                                <div class="col-sm-10">
                                    <input v-model="role.name" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">描述</label>
                                <div class="col-sm-10">
                                    <input v-model="role.desc" class="form-control">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button v-on:click="save" type="button" class="btn btn-primary">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </div>
</template>

<script>
    import Pagination from "../../components/pagination";
    import MiniPagination1 from "../../components/miniPagination1";
    import MiniPagination from "../../components/miniPagination";
    export default {
        components: {MiniPagination1, MiniPagination, Pagination},
        name: "system-role",
        data: function() {
            return {
                role: {},
                roles: [],
                users: [],
                roleUser: {},
                roleUsers: [],
                resources: [],
                roleResource: {},
                tree: {},
            }
        },
        mounted: function() {
            // sidebar激活样式方法一
            // this.$parent.activeSidebar("system-role-sidebar");
            let _this = this;
            _this.$refs.pagination.size = 10;
            _this.$refs.miniPagination.size = 10;
            _this.$refs.miniPagination1.size = 10;
            _this.getList(1);
        },
        methods: {

            /**
             * 移除用户角色
             * */
            removeRoleForUser: function (user) {
                let _this = this;
                //被删除角色的用户底色还原为白色
                Tool.removeObj(_this.roleUsers, user);
                _this.removeUserClass(user.loginName);
                let roleUsers = _this.roleUsers;
                for (let i = 0; i < roleUsers.length; i++) {
                    _this.addUserClass(roleUsers[i].loginName)
                }
            },

            /**
             * 保存发送请求。向后端发送即将拥有角色的用户列表，获取授权
             * */
            authUsers: function () {
                let _this = this;
                let userIds = [];
                let roleUsers = _this.roleUsers;
                for (let i = 0; i < roleUsers.length; i++) {
                    userIds.push(roleUsers[i].id)
                }
                let roleId = _this.role.id;
                _this.roleUser.userIdList = userIds;
                _this.roleUser.roleId = roleId;

                LocalStorage.remove(roleId);
                LocalStorage.remove(roleId+LOCAL_KEY_USERS);

                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roleUser/authorization', _this.roleUser).then((response) => {
                    Loading.hide();
                    let resp = response.data;
                    if (resp.success) {
                        Toast.success("角色授权成功！");
                    } else {
                        Toast.success("失败！");
                    }
                    $("#auth-modal").modal("hide");
                })
            },

            /**
             * 给用户添加角色权限，将用户添加到右边
             * */
            addAuth: function (user) {
                let _this = this;
                let roleUsers = _this.roleUsers;
                for (let i = 0; i < roleUsers.length; i++) {
                    if (user.id == roleUsers[i].id) {
                        _this.addUserClass(user.loginName);
                        return ;
                    }
                }
                _this.roleUsers.push(user);

                _this.addUserClass(user.loginName);
            },

            /**
             * 给每个用户添加id
             * */
            generatorId: function (user) {
                return user.loginName;
            },

            /**
             * 给每个用户添加id
             * */
            generatorIdIdx: function (user) {
                return user.loginName +"_Idx";
            },

            /*
            * 给用户列表清空样式
            * */
            removeUserClass: function (userLoginName) {
                $("#" + userLoginName).removeClass("loginName-blue");
                $("#" + userLoginName + "_Idx").removeClass("loginName-blue");
                console.log("正在删除样式", userLoginName)
            },

            /*
            * 给用户列表增加样式
            * */
            addUserClass: function (userLoginName) {
                setTimeout(function () {
                    // 被添加到右边的用户底色为蓝色
                    $("#" + userLoginName).addClass("loginName-blue");
                    $("#" + userLoginName + "_Idx").addClass("loginName-blue");
                }, 100);
            },

            /**
             * 给即将授权的用户分页
             * */
            getRoleUsersPage: function (page) {
                let _this = this;



            },

            /**
             * 给用户分页
             * */
            getUserPage: function (page) {
                let _this = this;



            },

            interval: function (roleId,start,len) {
                if (!start) {
                    start = 600;
                }
                if (!len) {
                    len = 1000;
                }
                let _this = this;
                let roleUsers = LocalStorage.get(roleId);
                let users = LocalStorage.get(LOCAL_KEY_USERS);

                for (let i = 0; i < users.length; i++) {
                    $("#" + users[i].loginName).removeClass("loginName-blue");
                    $("#" + users[i].loginName + "_Idx").removeClass("loginName-blue");
                }
                if (roleUsers == null) {
                    return ;
                } else {
                    for (let i = 0; i < roleUsers.length; i++) {
                        console.log("正在添加样式", roleUsers[i].id);
                        console.log("roleUsers["+i+"].id = ", roleUsers[i].id);
                        console.log("roleUsers["+i+"].id = ", roleUsers[i].id + "_Idx");
                        _this.addUserClass(roleUsers[i].loginName);
                        _this.addUserClass(roleUsers[i].loginName + "_Idx");
                    }
                }
            },

            /**
             * 打开添加角色授权窗口
             * */
            unfoldAuthWindow: function (role) {
                let _this = this;
                _this.role = $.extend({}, role);
                _this.users = [];
                _this.roleUsers = [];
                _this.getAllUser();
                _this.getlocalstor();
                //防止错误点击视频界面以外的位置而导致的视频关闭
                $("#auth-modal").modal({backdrop: 'static'});
                $("#auth-modal").modal("show");
            },

            /**
             * 获取用户列表
             * */
            getAllUser: function () {
                let _this = this;
                let users = LocalStorage.get(LOCAL_KEY_USERS);
                if (users != null) {
                    _this.users = users;
                    return ;
                }
                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/user/all').then((response)=>{
                    Loading.hide();
                    let resp = response.data;
                    LocalStorage.set(LOCAL_KEY_USERS,resp.content);
                    _this.users = resp.content;
                });
            },

            getlocalstor: function () {
                let _this = this;
                let roleId = _this.role.id;

                let roleUsersKey = LocalStorage.get(roleId+LOCAL_KEY_USERS);
                if(!roleUsersKey){
                    _this.getAllRoleUser();
                    return;
                }
                let roleUsers = LocalStorage.get(roleId);
                if(!roleUsers){
                    _this.getAllRoleUser();
                    return;
                }
                console.log("打开窗口：roleUsersKey = ", roleUsersKey);
                console.log("打开窗口：roleUsers = ", roleUsers);
                if (roleUsersKey.length != roleUsers.length) {
                    _this.getAllRoleUser();
                    return;
                } else {
                    let formData = new FormData();
                    for (let i = 0; i < roleUsersKey.length; i++) {
                        formData.append(roleUsersKey[i].id, roleUsersKey[i]);
                    }
                    for (let j = 0; j < roleUsers.length; j++) {
                        let newVar = formData.get(roleUsers[j].id);
                        if (roleUsers[j] != newVar) {
                            _this.getAllRoleUser();
                            return;
                        }
                    }
                }

                _this.roleUsers = roleUsers;
                console.log("使用缓存：roleUsers = ", roleUsers);
                _this.interval(roleId);
            },

            /**
             * 获取即将拥有角色权限的用户列表
             * */
            getAllRoleUser: function () {
                let _this = this;
                let roleId = _this.role.id;
                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roleUser/user',"roleId="+roleId).then((response)=>{
                    Loading.hide();
                    let resp = response.data;
                    let roleIdAndUserIdList = resp.content;
                    let users = _this.users;
                    for (let i = 0; i < roleIdAndUserIdList.length; i++) {
                        for (let j = 0; j < users.length; j++) {
                            if (roleIdAndUserIdList[i].userId == users[j].id) {
                                _this.roleUsers.push(users[j]);
                            }
                        }
                    }
                    LocalStorage.remove(roleId);
                    LocalStorage.remove(roleId+LOCAL_KEY_USERS);
                    LocalStorage.set(roleId,_this.roleUsers);
                    LocalStorage.set(roleId+LOCAL_KEY_USERS,_this.roleUsers);
                    _this.interval(roleId);
                })
            },

            /**
             * 展开资源窗口
             */
            unfoldResourceWindow: function (role) {
                let _this = this;
                _this.role = $.extend({}, role);
                _this.unfoldResource();
                $("#resource-modal").modal("show");
            },

            /**
             * 资源展示
             */
            unfoldResource: function () {
                let _this = this;
                Loading.show();
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/resource/list').then((response)=>{
                    Loading.hide();
                    let resp = response.data;
                    _this.resources = resp.content;
                    _this.initTree();
                    _this.roleResourceCheckNode();
                })

            },

            initTree:function() {
                let _this = this;
                let setting = {
                    // 复选框，就是打勾勾的那个框，这里需要。
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            idKey: "id",
                            pIdKey: "parent",
                            rootPId: "",
                            enable: true
                        }
                    }
                };

                let zNodes = _this.resources;

                _this.tree = $.fn.zTree.init($("#tree"), setting, zNodes);
                // 随自己意愿，可展开或合上所有的节点
                _this.tree.expandAll(true);
            },

            /**
             * 点击发送权限许可请求
             */
            send: function (role) {
                let _this = this;

                _this.role = $.extend({}, role);
                let resources = _this.tree.getCheckedNodes();
                let resourceIdList = [];
                if (resources.length == 0 || !resources || resources == null) {
                    Confirm.show("该角色没有任何权限，确定吗？", function () {
                        _this.authorization(resourceIdList);
                    });
                } else {
                    for (let i = 0; i < resources.length; i++) {
                        resourceIdList.push(resources[i].id);
                    }
                    _this.authorization(resourceIdList);
                }
            },

            /**
             * 请求授权
             * */
            authorization: function (resourceIdList) {
                let _this = this;
                let roleId = _this.role.id;
                _this.roleResource.resourceIdList = resourceIdList;
                _this.roleResource.roleId = roleId;

                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roleResource/authorization', _this.roleResource).then((response) => {
                    Loading.hide();
                    let resp = response.data;
                    if (resp.success) {
                        Toast.success("获得权限许可！");
                    } else {
                        Toast.success("授权失败！");
                    }
                    $("#resource-modal").modal("hide");
                })
            },

            /**
             * 显示角色拥有的权限
             * */
            roleResourceCheckNode: function () {
                let _this = this;
                Loading.show();
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/roleResource/check/node/' + _this.role.id).then((res)=>{
                    Loading.hide();
                    let response = res.data;
                    if (response.success == true) {
                        let roleResourceList = response.content;

                        // 先去掉原有的勾勾
                        _this.tree.checkAllNodes(false);
                        // 再勾选查询到的分类
                        for (let i = 0; i < roleResourceList.length; i++) {
                            let node = _this.tree.getNodeByParam("id", roleResourceList[i].resourceId);
                            _this.tree.checkNode(node, true);
                        }
                    }
                })
            },

            /**
             * 点击【新增】
             */
            add:function() {
                let _this = this;
                _this.role = {};
                $("#form-modal").modal("show");
            },
            /**
             * 点击【编辑】
             */
            edit:function(role) {
                let _this = this;
                _this.role = $.extend({}, role);
                $("#form-modal").modal("show");
            },
            /**
             * 列表查询
             */
            getList: function (page) {
                let _this = this;
                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/list',{
                    page: page,
                    size: _this.$refs.pagination.size,
                }).then((response)=>{
                    Loading.hide();
                    let resp = response.data;
                    _this.roles = resp.content.list;
                    _this.$refs.pagination.render(page, resp.content.total);

                })

            },
            /**
             * 点击【保存】
             */
            save:function() {
                let _this = this;
                //保存校验
                if (1 != 1
                    || !Validator.require(_this.role.name, "角色")
                    || !Validator.length(_this.role.name, "角色", 1, 50)
                    || !Validator.require(_this.role.desc, "描述")
                    || !Validator.length(_this.role.desc, "描述", 1, 100)
                ) {
                    return;
                }

                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/save', _this.role).then((response)=>{
                    Loading.hide();
                    let resp = response.data;
                    if (resp.success) {
                        $("#form-modal").modal("hide");
                        _this.getList(1);
                        Toast.success("保存成功！");
                    } else {
                        Toast.error(resp.message);
                    }
                })
            },
            /**
             * 点击【删除】
             */
            del(id) {
                let _this = this;
                Confirm.show("删除角色后不可恢复，确认删除？", function () {
                    Loading.show();
                    _this.$ajax.delete(process.env.VUE_APP_SERVER + '/system/admin/role/delete/' + id).then((response)=>{
                        Loading.hide();
                        let resp = response.data;
                        if (resp.success) {
                            _this.getList(1);
                            Toast.success("删除成功！");
                        }
                    })
                });
            }
        }
    }
</script>

<style scoped>
    .td-padding-right{
        padding-right: 0;
    }
    .td-padding-left{
        padding-left: 0;
    }
    .aastyle{
        display: block;
        width: 100%;
        height: auto;
    }
    .min{
        width: 8%;
    }
    .loginName-blue{
        background-color: deepskyblue;
    }
    a{
        text-decoration: none;
        outline:none;
    }
    a:hover, a:visited, a:link, a:active {
        color:#333;
    }
</style>